/*
Copyright (c) [2019年5月1日] [吴超]
[MBT_studio] is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
		 http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
*/
#include "stdafx.h"

#include "面/面.h"
#include "物体/物体.h"

#include <file_载入保存数据.h>
#include <字符串/str_字符串读写.h>
#include "STL模型加载保存.h"



void f_Ex加载STL模型(S_物体* ob, const std::string& path, S_设备环境& ctx) {
	FILE* f = fopen(path.c_str(), "rb");
	if (f) {
		S_Mesh* me = f_ob_getMesh(ob, E_物体网格元素类型::e_MT_面);

		char header[80] = "MBT STL File";
		int triangleCount = 1;

		fwrite(header, sizeof(char), 80, f);
		fwrite(&triangleCount, sizeof(int), 1, f);


		fclose(f);
	}
}


void f_Ex保存STL模型(S_物体* ob, const std::string& path, fp_坐标转换 fn) {
	FILE* f = fopen(path.c_str(), "wb");
	if (f) {
		
		typedef struct {
			vec3 normal;
			vec3 v1;
			vec3 v2;
			vec3 v3;
			int16 attribute;
		} S_Triangle;


		S_Mesh* me = f_ob_getMesh(ob, E_物体网格元素类型::e_MT_面);
		
		//char header[80] = "MBT STL File\0";
		char header[80] = {0};
		int32 triangleCount = me->m_索引->m_Mem.m_数量 / 3;
		uint32* index = f_buf_UI32_ptr(*me->m_索引);
		
		auto* vert = f_buf_VNT_ptr(*me->m_顶点);

		auto mat = f_mat44_构建旋转缩放矩阵(ob->m_变换);
		//auto mat = f_mat44_构建XYZ欧拉旋转矩阵(ob->m_变换);
		//auto mat = f_mat4_构建缩放矩阵(ob->m_变换.scale);
		//auto mat = f_mat44_构建XYZ变换矩阵(ob->m_变换);
		//S_Triangle* 三角形 = (S_Triangle*)malloc(sizeof(S_Triangle) * triangleCount);

		fwrite(header, sizeof(char), 80, f);
		fwrite(&triangleCount, sizeof(int32), 1, f);

		for (int32 i = 0; i < triangleCount; ++i) {
			//auto& e = vert[index[i*3]];

			S_Triangle triangle{};
			triangle.v1 = mat * vert[index[i * 3 + 0]].vert;
			triangle.v2 = mat * vert[index[i * 3 + 1]].vert;
			triangle.v3 = mat * vert[index[i * 3 + 2]].vert;

			if (fn) {
				triangle.v1 = fn(triangle.v1);
				triangle.v2 = fn(triangle.v2);
				triangle.v3 = fn(triangle.v3);
			}

			triangle.normal = f_surface_FaceNormal(triangle.v1, triangle.v2, triangle.v3);
			triangle.attribute = 0;

			fwrite(&triangle.normal, sizeof(vec3), 1, f);
			fwrite(&triangle.v1, sizeof(vec3), 1, f);
			fwrite(&triangle.v2, sizeof(vec3), 1, f);
			fwrite(&triangle.v3, sizeof(vec3), 1, f);
			fwrite(&triangle.attribute, sizeof(int16), 1, f);

			//三角形[i] = triangle;
		}


		

		
		fclose(f);
	}
}





